package com.system.insurance.controller;

import com.system.common.result.Result;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@Api(tags = "文件上传下载，PDFWord")
@Controller
@CrossOrigin(origins = "*")
@RequestMapping("/insurance/PDF")
public class FileUploadController {


    @Value("${urlPDF}")
    private String urlPDF;

    @PostMapping("/upload")
    public Result handleFileUpload(@RequestParam("file") MultipartFile file) {
//        String fileName = file.getOriginalFilename();
//        // 检查文件类型是否为Word或PDF
//        if (!(fileName.endsWith(".docx") || fileName.endsWith(".pdf"))) {
//            return Result.fail("Unsupported file type");
//        }
//
//        try {
//            // 实现文件保存的逻辑，例如保存到服务器的某个文件夹
//            // 这里需要实现文件保存的代码
//            // File savedFile = new File("targetDirectory" + fileName);
//            // file.transferTo(savedFile);
//
//            return Result.ok(fileName);
//        } catch (Exception e) {
//            return Result.fail(e.getMessage());
//        }
        //获取文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件格式
        String subFile = originalFilename.substring(originalFilename.lastIndexOf("."));
        //生成随机的文件名字
        String filename = UUID.randomUUID().toString() + subFile;
        File file1 = new File(urlPDF);
        //判断存放图片的目录是否存在，不存在则进行创建
        if (!file1.exists()) {
            file1.mkdirs();
        }


        try {
            //错误示范
//            file.transferTo(new File(file1 + filename));
            //将临时文件转存到指定位置
            file.transferTo(new File(urlPDF + filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.ok(filename);

    }


    /**
     * 文件下载
     *
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(urlPDF + name));
            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            // 设置内容类型为Word文档
            response.setContentType("application/msword");

            // 设置内容类型为PDF
            response.setContentType("application/pdf");
            // 设置文件名
//            response.setHeader("Content-Disposition", "attachment; filename=\"example.doc\"");

            // 设置文件名
//            response.setHeader("Content-Disposition", "attachment; filename=\"example.pdf\"");


            int len = 0;
//            byte[] bytes = new byte[1024];
            byte[] bytes = new byte[4096];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            outputStream.close();
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

